﻿
using System.Collections;
using System.Collections.Generic;
using Koroutine.Runtime.Condition;
using UnityEngine;

namespace Koroutine.Runtime.Core
{
    internal class CoroutineContext
    {
        public IEnumerator Coroutine;
        public ICondition Condition;
    }

    internal enum CoroutineExitFlag
    {
        None,
        BreakTop,
        BreakAll
    }
    
    public class CoroutineExecutionHandle
    {
        internal readonly Stack<CoroutineContext> CoroutineStack = new Stack<CoroutineContext>();
        internal IEnumerator ActiveEnumerator => CoroutineStack.Peek().Coroutine;

        internal CoroutineExitFlag ExitFlag = CoroutineExitFlag.None;

        internal ICondition ActiveCondition
        {
            get { return CoroutineStack.Peek().Condition; }
            set { CoroutineStack.Peek().Condition = value; }
        }

        public void TakeOver(IEnumerator coroutine)
        {
            if (CoroutineStack.Count > 0)
                CoroutineStack.Pop();
            CoroutineStack.Push(new CoroutineContext() { Coroutine = coroutine });
        }

        public void Cover(IEnumerator coroutine)
        {
            CoroutineStack.Push(new CoroutineContext() { Coroutine = coroutine });
        }

        public void Break(bool all = false)
        {
            ExitFlag = all ? CoroutineExitFlag.BreakAll : CoroutineExitFlag.BreakTop;
        }
    }
}